//
//  UserInfoManager.m
//  MemberProject
//
//  Created by MAC OS X on 15/4/14.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "UserInfoManager.h"
#import "LoginViewController.h"

//文件夹相对路径
#define kFileDirectory     @"/Log"
#define kLogDirectory      @"/LoginUser"



@implementation UserInfoManager
+ (UserInfoManager *)sharedManager
{
    static UserInfoManager *sharedUserInfoManagerInstance = nil;
    
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedUserInfoManagerInstance = [[self alloc] init];
        [sharedUserInfoManagerInstance createDirectoty];
//        [sharedUserInfoManagerInstance refreshUserInfo];
    });
    return sharedUserInfoManagerInstance;
}

/*
 存储日志路径
 */
- (NSString *)getFilePath:(NSString *)fileName
{
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [[array objectAtIndex:0] stringByAppendingString:fileName];
}


#pragma mark 创建文件目录
- (BOOL)createDirectoty
{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *logDirectory = [self getFilePath:kFileDirectory];
    
    return [fileManager createDirectoryAtPath:logDirectory
                  withIntermediateDirectories:YES
                                   attributes:nil
                                        error:nil];
}

#pragma mark 写入本地日志
-(void)writeLocalLog:(NSDictionary *)dic
{
    [self removeUserFile];
    NSMutableDictionary *userDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    for (NSString *key in userDic.allKeys) {
        NSObject *object = userDic[key];
        if ([object isKindOfClass:[NSNull class]]) {
            [userDic setValue:@"" forKey:key];
        }
    }
    
    
    NSString *path = [self getFilePath:kFileDirectory];
    NSString *filePath =[NSString stringWithFormat:@"%@%@",path,kLogDirectory];
    
    [userDic writeToFile:filePath atomically:YES];
    
}

#pragma mark 获取本地日志
-(NSDictionary *)getLocalLog
{
    NSString *path = [[UserInfoManager sharedManager] getFilePath:kFileDirectory];
    NSString *localPath = [NSString stringWithFormat:@"%@%@",path,kLogDirectory];
//    [self removeUserFile];
    
    return [NSDictionary dictionaryWithContentsOfFile:localPath];
}

#pragma mark 修改密码
-(void)changePassword:(NSString *)newPasswordMD5
{
    NSDictionary *userDic = [self getLocalLog];
    NSMutableDictionary *newDic = [[NSMutableDictionary alloc]initWithDictionary:userDic];
    [newDic setValue:newPasswordMD5 forKey:@"loginPassword"];
    [self writeLocalLog:newDic];
}

#pragma mark 删除文件
-(void)removeUserFile
{
    // 文件存放目录
    NSString *filePath = [self getFilePath:[NSString stringWithFormat:@"%@%@",kFileDirectory,kLogDirectory]];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    BOOL bRet = [fileMgr fileExistsAtPath:filePath];
    if (bRet) {
        //
        NSError *err;
        [fileMgr removeItemAtPath:filePath error:&err];
    }
}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(void)popAlertView
{
    UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"提示" message:@"你的登录密码已经修改" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertV show];
}
#pragma mark 点击确定后
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIViewController *currentVC = [self getCurrentVC];
    if (![currentVC isKindOfClass:[MenuViewController class]]) {
        [currentVC.navigationController popViewControllerAnimated:YES];
    }
    
}

#pragma mark 更新内容

-(void)refreshUserInfo
{
    //刷新数据
    CSResultBlock refreshBlock = ^(NSDictionary *result){
        ModelUser *user = [ModelUser getUserForDic:result];
        [UserInfoManager sharedManager].modelMser = user;
        [self writeLocalLog:result];
        
        
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationRefreshUserInfo object:nil];
        
    };
    
    //密码错了，退出
    CSVoidBlock loginOutBlock = ^(void)
    {
        [UserInfoManager sharedManager].modelMser = nil;
        [self removeUserFile];
        [self popAlertView];
        [[NSUserDefaults standardUserDefaults]setValue:loginNO forKey:ISAlreadyLogin];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationDelUserInfo object:nil];
    };
    
    
    
    
}

#pragma mark 是否呈现登陆界面
-(void)presentLoginViewController:(UIViewController *)VC andIsLogin:(CSVoidBlock)successBlock
{
    NSString *isLogin =[[NSUserDefaults standardUserDefaults]valueForKey:ISAlreadyLogin];
    if (isLogin !=nil&&[isLogin isEqualToString:loginYES] )
    {
        successBlock();
    }else
    {
        LoginViewController *loginVC = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
        [VC presentViewController:loginVC animated:YES completion:nil];
    }
    
}



@end
